# coding: utf-8
from datetime import datetime

from sqlalchemy import Column, Integer, String, DateTime, TEXT
from sqlalchemy.orm import Session

from .base import BaseModel


class HistoryViewTabelModel(BaseModel):
    __tablename__ = 'history_view'
    id = Column(Integer, autoincrement=True, primary_key=True)
    title = Column(String(255))
    description = Column(TEXT)
    url = Column(TEXT)
    create_time = Column(DateTime, default=datetime.now)


# @check_session
def history_view_exist(url: str, session: Session = None):
    """
    检查是否存在历史记录
    :param url:
    :param session:
    :return:
    """
    result = session.query(HistoryViewTabelModel).filter(HistoryViewTabelModel.url == url).first()
    if result:
        return True
    else:
        return False


# @check_session
def add_history_view(title: str, description: str, url: str, session: Session = None):
    """"
    添加历史记录
    """
    if history_view_exist(url, session):
        return
    history_view = HistoryViewTabelModel(title=title, description=description, url=url)
    session.add(history_view)
    session.commit()


# @check_session
def history_view_list(session: Session = None):
    history_views = session.query(HistoryViewTabelModel).all()
    return history_views


# @check_session
def delete_history_view(history_view_id: int, session: Session = None):
    """
    删除历史记录
    :param history_view_id:
    :param session:
    :return:
    """
    history_view = session.query(HistoryViewTabelModel).filter(HistoryViewTabelModel.id == history_view_id).first()
    print(history_view)
    if history_view:
        session.delete(history_view)
    session.commit()


def clear_history_view(session: Session = None):
    """
    清空历史记录
    :param session:
    :return:
    """
    session.query(HistoryViewTabelModel).delete()
    session.commit()
